<template>
    <Card dis-hover :bordered="false">
        <Form>
            <Row :gutter="24" type="flex" class="ivu-mb-16">
                <Col>
                <Button v-hasC="{
                    name: 'automation-push-create-push',
                    flag: 'v1/automation/push/create-push',
                }" type="primary" @click="handleOpenDrawer(-1)">新增</Button>
                </Col>
            </Row>
        </Form>
        <div class="i-table-no-border">
            <Table highlight-row ref="table" :columns="columns" :loading="loading" :data="data">
                <template slot="room" slot-scope="{ row }">
                    <tag v-for="item in row.room" :key="item.index">{{
                        item
                    }}</tag>
                </template>
                <template slot-scope="{ row }" slot="info">
                    <a v-hasC="{
                        name: 'automation-push-update-push',
                        flag: 'v1/automation/push/update-push',
                    }" href="javaScript:;" @click="handleOpenDrawer(row)">编辑</a>
                    <Divider v-hasCC="[
                        {
                            name: 'automation-push-update-push',
                            flag: 'v1/automation/push/update-push',
                        },
                        {
                            name: '-v1-automation-push-delete-push',
                            flag: 'v1/automation/push/delete-push',
                        },
                    ]" type="vertical" />
                    <a v-hasC="{
                        name: '-v1-automation-push-delete-push',
                        flag: 'v1/automation/push/delete-push',
                    }" @click="deletePush(row)">删除</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page show-total show-elevator show-sizer :total="total" :current.sync="params.page"
                      :page-size="params.pageSize" :page-size-opts="pageOpts" @on-change="formSize"
                      @on-page-size-change="formChangePage" />
            </div>
            <Modal v-model="modal" width="650" :title="edit ? `编辑` : `新增`" :mask-closable="false"
                   @on-cancel="handleDrawerCancel(modalname)">
                <Form :ref="modalname" :model="formItem" :rules="createRules" :label-width="100">
                    <FormItem label="数据类型：" prop="source">
                        <RadioGroup v-model="formItem.source" @on-change="changeTitle">
                            <Radio label="诊室">诊室</Radio>
                            <Radio label="部门">部门</Radio>
                            <Radio label="一级病种">一级病种</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem v-if="formItem.source === '一级病种'" label="一级病种" prop="diseases" :rules="{
                        required: true,
                        type: 'array',
                        message: '请选择一级病种',
                        trigger: 'change',
                    }">
                        <Select multiple v-model="formItem.diseases" :max-tag-count="3" placeholder="请选择一级病种">
                            <Option v-for="item in diseasesList" :value="item.value" :key="item.value">{{ item.label }}
                            </Option>
                        </Select>
                    </FormItem>
                    <FormItem v-if="formItem.source === '诊室'" label="诊室：" prop="room" :rules="{
                        required: true,
                        type: 'array',
                        message: '请选择诊室',
                        trigger: 'change',
                    }">
                        <Select multiple v-model="formItem.room" :max-tag-count="3" placeholder="请选择诊室">
                            <Option v-for="item in roomList" :value="item.value" :key="item.value">{{ item.label }}
                            </Option>
                        </Select>
                    </FormItem>
                    <template v-if="formItem.source === '部门'">
                        <FormItem v-for="(items, allIndex) in formItem.departments" :key="allIndex" label="部门：" :prop="
                            'departments.' + allIndex + '.department_ids'
                        " :rules="{
                            required: true,
                            message: '请选择部门',
                            trigger: 'change',
                        }">
                            <Select v-model="
                                        formItem.departments[allIndex]
                                            .department_ids
                                    " class="ivu-mr-8" v-width="100" placeholder="请选择部门"
                                    @on-change="changeDepartment(allIndex)">
                                <Option :value="item.value" v-for="(item, index) in department" :key="index">{{
                                item.label }}</Option>
                            </Select>
                            <Select v-model="formItem.departments[allIndex].role" :max-tag-count="2" multiple
                                    v-width="250" placeholder="请选择人员" v-if="
                                        formItem.departments[allIndex]
                                            .department_ids
                                    ">
                                <Option :value="item.value" v-for="(item, index) in role[allIndex]" :key="index">{{
                                item.label }}</Option>
                            </Select>
                            <Button v-if="
                                allIndex === formItem.departments.length - 1
                            " style="margin-left: 15px;" @click="addDepartment_id">新增</Button>
                            <Button v-if="allIndex !== 0" style="margin-left: 15px;"
                                    @click="deleteDepartment_id(allIndex)">删除</Button>
                        </FormItem>
                    </template>
                    <FormItem label="钉钉token：" prop="token">
                        <Input type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" v-model="formItem.token"
                               placeholder="请输入钉钉token" />
                    </FormItem>
                </Form>
                <div slot="footer">
                    <Button @click="handleDrawerCancel(modalname)">取消</Button>
                    <Button type="primary" :loading="remarksloading" @click="handleSubmit(modalname)">确定</Button>
                </div>
            </Modal>
        </div>
    </Card>
</template>

<script>
    import {
        alreadyPush,
        addAlreadyPush,
        editAlreadyPush,
        automationPush,
        getDepartmentRole
    } from '@/api/TApi/index.js';
    export default {
        /*  import引入的组件注入到components对象中使用  */
        components: {},
        data () {
            const validateToken = (rule, value, callback) => {
                if (value.includes('https://')) {
                    callback();
                } else {
                    callback(new Error('请正确输入包含https的钉钉token'));
                }
            };
            return {
                total: 0, //  分页总数
                remarksloading: false,
                pageOpts: [10, 20, 30, 50], //  分页每页数量
                params: { page: 1, pageSize: 10 }, //  请求参数
                edit: true, //  编辑true,新增false
                loading: false, //  加载中
                modal: false, //  模态框开启属性
                modalname: 'formItem',
                grid: { xl: 4, lg: 8, md: 12, sm: 24, xs: 24 }, //  layout布局
                roomList: [],
                diseasesList: [],
                role: [],
                isEdit: {},
                columns: [
                    {
                        title: '名称',
                        key: 'type_name',
                        tooltip: true,
                        ellipsis: true,
                        minWidth: 118
                    },
                    {
                        title: '钉钉机器人token',
                        key: 'dingtalk_id',
                        tooltip: true,
                        minWidth: 300
                    },
                    {
                        title: '操作人',
                        key: 'operation_name',
                        width: 100
                    },
                    {
                        title: '更新时间',
                        key: 'updated_at',
                        minWidth: 150
                    },
                    { title: '操作', slot: 'info', width: 150 }
                ], // 列表表头
                data: [], // 列表数据
                department: [],
                formItem: {
                    room: [],
                    diseases: [],
                    token: '',
                    role: [],
                    departments: [
                        {
                            department_ids: '',
                            role: []
                        }
                    ],
                    source: '诊室'
                },
                // 模态框数据
                createRules: {
                    // room: [
                    //   {
                    //     type: "array",
                    //     required: true,
                    //     message: "请选择诊室",
                    //     trigger: "change",
                    //   },
                    // ],
                    token: [
                        {
                            validator: validateToken,
                            trigger: 'blur',
                            required: true
                            // message: "请输入钉钉token",
                            // trigger: "blur",
                        }
                    ],
                    source: [
                        {
                            required: true,
                            message: '请选数据类型',
                            trigger: 'change'
                        }
                    ]
                } // 模态框验证规则
            };
        },
        /* 监听属性 类似于data概念 */
        computed: {},
        watch: {},
        /* 创建完成能访问this实例 */
        created () { },
        /* 函数方法集合 */
        methods: {
            addDepartment_id () {
                this.formItem.departments.push({
                    department_ids: '',
                    role: [],
                    dataType: ''
                });
            },
            deleteDepartment_id (index) {
                this.formItem.departments.splice(index, 1);
            },
            changeTitle (value) {
                if (value) {
                    let data = JSON.parse(JSON.stringify(this.formItem));
                    this.$refs[this.modalname].resetFields();
                    this.formItem = data;
                }
            },
            /* @函数功能: 初始化 */
            initial () {
                this.askData();
            },
            changeDepartment (value) {
                this.formItem.departments[value].role = [];
                let id = this.formItem.departments[value].department_ids;
                getDepartmentRole({ department_id: id }).then((res) => {
                    this.$set(this.role, value, res);
                });
            },
            /* @函数功能: 请求数据 */
            askData () {
                alreadyPush(this.params).then((res) => {
                    this.data = res.list.list;
                    this.roomList = res.clinic;
                    this.department = res.department;
                    this.diseasesList = res.diseases,
                    this.total = res.list.total;
                });
            },
            deletePush (row) {
                this.$Modal.confirm({
                    title: '删除提示',
                    content: '请确认是否删除到诊提醒设置？',
                    loading: true,
                    onOk: () => {
                        automationPush({
                            id: row.id
                        })
                            .then((res) => {
                                this.$Message.success('删除成功');
                                this.$Modal.remove();
                                this.askData();
                            })
                            .catch(() => {
                                this.$Modal.remove();
                        });
                    }
                });
            },
            /* @函数功能: 分页 */
            formSize (e) {
                this.params.page = e;
                this.askData();
            },
            /* @函数功能: 每页数量 */
            formChangePage (e) {
                this.params.pageSize = e;
                this.askData();
            },
            /* @函数功能: 打开新增或编辑 */
            handleOpenDrawer (row) {
                this.$refs[this.modalname].resetFields();
                this.formItem.room = [];
                this.formItem.role = [];
                this.formItem.source = '诊室';
                if (row === -1) {
                    this.edit = false;
                    this.modal = true;
                } else {
                    this.edit = true;
                    this.isEdit = row;
                    this.formItem.departments = [];
                    this.formItem.token = row.dingtalk_id;
                    if (row.date_type === '2') {
                        row.relation_id.split(',').forEach((ee) => {
                            this.formItem.departments.push({
                                department_ids: ee,
                                role: []
                            });
                        });
                        Promise.all(
                            row.relation_id.split(',').map((ee) => {
                                return getDepartmentRole({ department_id: ee });
                            })
                        ).then((res) => {
                            this.formItem.source = '部门';
                            this.role = res;
                            this.modal = true;
                        });
                    } else if (row.date_type === '3') {
                        Promise.all(
                            row.departmen_id.map((ee) => {
                                return getDepartmentRole({ department_id: ee });
                            })
                        ).then((res) => {
                            this.role = res;
                            row.departmen_id.forEach((ee, index) => {
                                let role = [];
                                row.relation_id.split(',').forEach((ees) => {
                                    res[index].forEach((vv) => {
                                        if (vv.value === ees) role.push(ees);
                                    });
                                });
                                this.formItem.departments.push({
                                    department_ids: ee,
                                    role
                                });
                            });
                            this.formItem.source = '部门';
                            this.modal = true;
                        });
                    } else if (row.date_type === '1') {
                        this.formItem.departments = [
                            {
                                department_ids: '',
                                role: []
                            }
                        ];
                        this.formItem.room = row.relation_id.split(',');
                        this.modal = true;
                    }else if(row.date_type === '6'){
                        this.formItem.source = '一级病种';
                        this.formItem.departments = [
                            {
                                department_ids: '',
                                role: []
                            }
                        ];
                        this.formItem.diseases = row.relation_id.split(',');
                        this.modal = true;
                    }
                }
            },
            /* @函数功能: 新增或编辑提交 */
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let params = {};
                        if (this.formItem.source === '诊室') {
                            params.list = [
                                {
                                    date_type: 1,
                                    relation_id: this.formItem.room.join(','),
                                    dingtalk_id: this.formItem.token
                                }
                            ];
                        } else if (this.formItem.source === '部门') {
                            let list = this.formItem.departments.map((ee) => {
                                return {
                                    relation_id: ee.role.length
                                        ? ee.role.join(',')
                                        : ee.department_ids,
                                    dingtalk_id: this.formItem.token,
                                    date_type: ee.role.length ? 3 : 2
                                };
                            });
                            params.list = list;
                        }else if (this.formItem.source === '一级病种') {
                            params.list = [
                                {
                                    date_type: 6,
                                    relation_id: this.formItem.diseases.join(','),
                                    dingtalk_id: this.formItem.token
                                }
                            ];
                        }
                        if (this.edit) {
                            params.id = this.isEdit.id;
                            editAlreadyPush(params)
                                .then((res) => {
                                    this.askData();
                                    this.$Message.success('编辑成功');
                                    this.modal = false;
                                    this.formItem = {
                                        room: [],
                                        token: '',
                                        role: [],
                                        departments: [
                                            {
                                                department_ids: '',
                                                role: []
                                            }
                                        ],
                                        source: '诊室'
                                    };
                                })
                                .finally(() => {
                                    this.remarksloading = false;
                            });
                        } else {
                            addAlreadyPush(params)
                                .then((res) => {
                                    this.askData();
                                    this.$Message.success('新增成功');
                                    this.modal = false;
                                    this.formItem = {
                                        room: [],
                                        token: '',
                                        role: [],
                                        departments: [
                                            {
                                                department_ids: '',
                                                role: []
                                            }
                                        ],
                                        source: '诊室'
                                    };
                                })
                                .finally(() => {
                                    this.remarksloading = false;
                            });
                        }
                    }
                });
            },
            /* @函数功能: 取消新增或编辑 */
            handleDrawerCancel (name) {
                this.formItem = {
                    room: [],
                    token: '',
                    role: [],
                    departments: [
                        {
                            department_ids: '',
                            role: []
                        }
                    ],
                    source: '诊室'
                };
                this.modal = false;
            }
        },
        /* 挂载完成能访问DOM元素 */
        mounted () {
            this.initial();
        },
        /* 创建之前 */
        beforeCreate () { },
        /* 挂载之前 */
        beforeMount () { },
        /* 更新之前 */
        beforeUpdate () { },
        /* 更新之后 */
        updated () { },
        /* 销毁之前 */
        beforeDestroy () { },
        /* 销毁完成 */
        destroyed () { },
        /* 有keep-alive缓存即会触发 */
        activated () { }
    };
</script>

<style lang="less" scoped></style>
